// pages/clockin/clockin.js
var QQMapWX = require('../../utils/qqmap-wx-jssdk');
var config = require("../../utils/config")
var qqmapsdk = new QQMapWX({
  key: config.qq_key // 必填
});
var util = require("../../utils/util");
var timeid;
const {
  http
} = require("../../utils/apiutils");

import {getMore} from '../../utils/tools'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    scrollH:90,
    tabs:[
      {
        title:'考勤打卡',
        name:1
      },
      {
        title:'打卡记录',
        name:2
      }
    ],
    tabActive:1,
    active:1,
    type: [],
    fileList: [],
    gwInfo: {},
    latitude: "",
    ds: "",
    time: util.formatTime(new Date()),
    longitude: "",
    dataList: [],
    lInfo: null,
    newTime: "",
    imgList: [],
    imgStr: [],
    spx: 0,
    jobData: null,
    dktype: {
      ds: true,
      tm: true,
    },
    sbsj:'',
    xbsj:'',
    pageNo:1,
    hasMore:true,
    loading:false,
    pageSize:10,
    recordList:[]
  },

  onclickQY: function () {

    var me = this.data.lInfo;
    var job = {}
    if (this.data.jobData.type == 2 && this.data.gwInfo.type == 1) {

      job = {
        lat: this.data.jobData.gatherLat,
        lng: this.data.jobData.gatherLng,
        address: this.data.jobData.gatherAddress,
      }
    } else {
      job = {
        lat: this.data.jobData.lat,
        lng: this.data.jobData.lng,
        address: this.data.jobData.workPlace,
      }
    }
    console.log("-------", me, job);
    var data = {
      me,
      job
    }
    try {
      wx.setStorageSync('lc', JSON.stringify(data))
    } catch (e) {}
    wx.navigateTo({
      url: '/pages/clockinL/clockinL',
    })

  },
  beforeRead(event) {
    const {
      file,
      callback
    } = event.detail;
    callback(file.type === 'image');
    const {
      fileList = []
    } = this.data;
    fileList.push({
      ...file,
      url: file.url
    });
    this.setData({
      fileList
    });
    // console.log("-------------",file);
  },
  deletePic: function (e) {
    console.log("-----------", e);
  },
  afterRead: function () {

  },
  onclicktype: function (e) {
    let index = e.currentTarget.dataset.index;
    var arr = this.data.type;
    var c = arr.indexOf(index);
    if (c > 0) {
      arr.splice(c, 1);
    } else {
      arr.push(index);
    }
    this.setData({
      type: arr,
    })
    console.log("------------", index, arr);
  },
  onclicktHis: function () {

    let info = encodeURIComponent(JSON.stringify(this.data.gwInfo));
    wx.navigateTo({
      url: '/pages/calendar/calendar?info=' + info,
    })
  },
  onclickPz: function (e) {
    console.log("-------拍照打卡--")
    wx.navigateTo({
      url: '/pages/me/pages/photograph/photograph?type='+e.currentTarget.dataset.key,
    })
  },
  onclickDaohang: function () {
    wx.openLocation({
      latitude: Number(this.data.jobData.gatherLat),
      longitude: Number(this.data.jobData.gatherLng),
      name: this.data.jobData.gatherAddress,
      address: this.data.jobData.gatherAddress,
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  getDateInfo() {
    var date = new Date()
    // const year = date.getFullYear()
    // const month = date.getMonth() + 1
    // const day = date.getDate()
    const hour = date.getHours() >= 10 ? date.getHours() : "0" + date.getHours()
    const minute = date.getMinutes() >= 10 ? date.getMinutes() : "0" + date.getMinutes()
    const second = date.getSeconds() >= 10 ? date.getSeconds() : "0" + date.getSeconds()
    return hour + ":" + minute + ":" + second;

  },

  onLoad: function (options) {
    var that = this;
    timeid = setInterval(function () {
      that.setData({
        newTime: that.getDateInfo()
      })
      console.log("---------定时器----")
    }, 1000);
    // this.getLocation()
    let info = JSON.parse(decodeURIComponent(options.data))

    this.setData({
      gwInfo: info,
    })
    var str = ""
    if (info.type == 1) {
      str = "到岗打卡"
    } else if (info.type == 2) {
      str = "工作打卡"
    } else if (info.type == 3) {
      str = "完成工作打卡"
    }
    wx.setNavigationBarTitle({
      title: str,
    })
    this.formSubmit();
    this.getclockInList()
    this.getJobData(this.data.gwInfo.jobId)
    var that = this;
    wx.getSystemInfo({
      success: (res) => {
        var spx = (res.windowHeight * (750 / res.windowWidth));
        that.setData({
          spx: spx - 1100
        })
        console.log("-------spx-----", spx);
      },
    })

  },

  dkPd: function () {
    if (this.data.jobData && this.data.lInfo) {

      if (this.data.gwInfo.type == 1) {
        var start = this.data.jobData.asOfTime;
        // console.log("-------开始工作时间-", start);
        if (this.data.jobData.type == 1) {

        } else {
          start = this.data.gwInfo.interviewDate + " 23:59:59";
        }
        var timestamp = parseInt(new Date().getTime() / 1000); // 当前时间戳
        start = start.substring(0, 19);
        start = start.replace(/-/g, '/'); //必须把日期'-'转为'/'
        var timestamp1 = parseInt(new Date(start).getTime() / 1000);
        if (timestamp1 < timestamp) {
          this.setData({
            "dktype.tm": false,
          })
          console.log("------打卡时间范围外----")
        } else {
          console.log("------打卡时间范围内----")
        }
      }
      let ds = 0;
      if (this.data.gwInfo.type == 1 && this.data.jobData.type == 2 && this.data.jobData.gatherLat) {
        console.log("------到岗打卡---", this.data.lInfo)
        ds = util.getDistance(this.data.lInfo.lat, this.data.lInfo.lng, this.data.jobData.gatherLat, this.data.jobData.gatherLng);
      } else {
        console.log("------工作打卡---")
        ds = util.getDistance(this.data.lInfo.lat, this.data.lInfo.lng, this.data.jobData.lat, this.data.jobData.lng);
      }
      console.log("-------距离打卡地点---", ds, "公里")

      if (ds > 2) {
        this.setData({
          "dktype.ds": false,

        })
      }
      this.setData({
        "ds": ds + "km",
      })
    }

  },
  onlcikCall: function () {
    wx.makePhoneCall({
      phoneNumber: this.data.jobData.contactPhone,
    })
  },
  getJobData: function (id) {

    var that = this;
    wx.showLoading({
      title: '加载中...',
    })
    http.getJobData(id,
      function (res) {
        wx.hideLoading()
        console.log("------岗位详情---", res);
        if (res.code == 0) {
          let db = res.data;
          that.setData({
            jobData: db
          })
          that.dkPd()
        } else {
          wx.showToast({
            title: res.message,
            icon: "none",
          })
        }
      },
      function (err) {
        wx.hideLoading()
      })
  },
  getclockInList: function () {
    var data = {
      id: this.data.gwInfo.id,
      // time: this.data.time,
    }
    var that = this;

    http.getclockInList(data,
      function (res) {
        console.log("------打卡信息--", res);
        if (res.code == 0) {
          let arr = res.data;
          arr.forEach(element => {
            if (element.imagePath != "") {
              element.imgList = element.imagePath.split(",")
            } else {
              element.imgList = []
            }
          });
          console.log("------------", arr);
          that.setData({
            dataList: arr.reverse(),
          })
        } else {
          wx.showToast({
            title: res.message,
            icon: "none",
          })
        }


      },
      function (err) {
        wx.hideLoading()
      })
    console.log("----------", data);
  },
  //在Page({})中使用下列代码
  //触发表单提交事件，调用接口
  formSubmit(e) {
    var that = this;
    wx.showLoading({
      title: '定位中...',
    })
    qqmapsdk.reverseGeocoder({
      /**
       *
       //String格式
        location: '39.984060,116.307520',
      */
      //get_poi: 1, //是否返回周边POI列表：1.返回；0不返回(默认),非必须参数
      success: function (res) { //成功后的回调
        let info = res.result;
        console.log("-------", info.ad_info);
        wx.hideLoading({
          success: (res) => {},
        })
        var data = {
          address: info.address,
          lat: info.location.lat,
          lng: info.location.lng,
        }
        that.setData({
          lInfo: data,
        })
        that.dkPd()
      },
      fail: function (error) {
        wx.hideLoading({
          success: (res) => {},
        })
      },
      complete: function (res) {
        wx.hideLoading({
          success: (res) => {},
        })
      }
    })
  },

  // getLocation: function () {
  //   wx.getLocation({
  //     type: 'gcj02',
  //     success: function (res) {
  //       console.log(res);
  //       that.data.latitude = res.latitude;
  //       that.data.longitude = res.longitude;

  //     },
  //   })
  // },



  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  uploadFlie: function (src, index) {
    var data = {
      url: src,
      name: "file",
      formData: {},
    }
    var that = this;
    wx.showLoading({
      title: '上传中...',
    })
    http.uploadFlie(data,
      function (res) {
        wx.hideLoading()
        console.log("------上传图片--", res);
        if (res.code == 0) {
          that.data.imgStr.push(res.data);
          if (index == that.data.imgList.length - 1) {
            that.subclockIn();
          } else {
            that.uploadFlie(that.data.imgList[index + 1], index + 1)
          }

        } else {
          wx.showToast({
            title: res.message,
            icon: "none",
          })
        }
      },
      function (err) {
        wx.hideLoading()
      })


  },
  dkLz(){
    var that = this;
    http.getclockInInfo(this.data.gwInfo.id,
      function (res) {
        
      },
      function (err) {
        wx.hideLoading()
      })
  },
  //开始打卡
  subclockIn: function () {

    var mode = 2
    var that = this;
    if (that.data.imgStr.length > 0) {
      mode = 1
    }
    if (!that.data.lInfo.lng) {
      wx.showToast({
        title: '无法获取您的位置微信，暂无法打卡，请点击重新定位后再次打卡',
        icon: "none",
      })
      return
    }
    var anomaly = 0;
    if (!this.data.dktype.ds && this.data.dktype.tm) {
      anomaly = 3
    } else if (!this.data.dktype.ds) {
      anomaly = 1

    } else if (!this.data.dktype.tm) {
      anomaly = 2
    }
    var data = {
      "type": that.data.gwInfo.type, // 1 到达现场打卡 2 工作打卡 3 完成打卡
      "lat": that.data.lInfo.lat, // 打卡位置 维度
      "lng": that.data.lInfo.lng, // 打卡位置 经度
      "address": that.data.lInfo.address, // 打卡位置
      "mode": mode, // 1 拍照打卡 2 直接打卡
      "imagePath": that.data.imgStr.join(","), // (可选) 照片地址，拍照打卡必须传递,
      "anomaly": anomaly, //打卡状态
    }
    var that = this;
    
    http.clockIn(this.data.gwInfo.id, data,
      function (res) {
        console.log("------上报打卡--", res);
        if (res.code == 0) {
          wx.showToast({
            title: '打卡成功',
            icon: "none",
            duration: 5000
          })
          that.setData({
            imgList: [],
          })
          if (that.data.gwInfo.type == 3) {
            that.dkLz()
            wx.showModal({
              title: "提示",
              content: "您已完成该工作，请等待工资结算",
              showCancel: false,
              confirmText: "我知道",
              success: function (res) {
                if (res.confirm) {
                  wx.navigateBack({
                    delta: 2,
                  })
                }
              }
            })
          }
          if (that.data.gwInfo.type == 1) {
            wx.showToast({
              title: '打卡成功',
              icon: "none",
            })
            var info = that.data.gwInfo;
            wx.setNavigationBarTitle({
              title: "工作打卡",
            })
            info.type = 2;
            that.setData({
              gwInfo: info,
            })
            wx.setNavigationBarTitle({
              title: '工作打卡',
            })
          } else {
            wx.showToast({
              title: '打卡成功',
              icon: "none",
            })
          }
          that.getclockInList();
        } else {
          wx.showToast({
            title: res.message,
            icon: "none",
          })
        }
      },
      function (err) {
        wx.hideLoading()
      })

  },
  onclickDk: function () {
    var thta = this;
    if (this.data.gwInfo.type == 3) {
      var that = this;
      wx.showModal({
        title: "提示",
        content: "本次打卡后工作将会变更为离职状态,您确定已完成工作了",
        success: function (res) {
          if (res.confirm) {
            if (that.data.imgList.length > 0) {
              that.uploadFlie(that.data.imgList[0], 0);
            } else {
              that.subclockIn()
            }
          }
        }
      })
    } else {
      if (this.data.imgList.length > 0) {
        this.uploadFlie(this.data.imgList[0], 0);
      } else {
        if (this.data.gwInfo.type == 1) {
          if (!this.data.dktype.tm) {
            var that = this;
            wx.showModal({
              title: "提示",
              content: "打卡已超过对应的时间确认打卡吗",
              success: function (res) {
                if (res.confirm) {
                  if (that.data.imgList.length > 0) {
                    that.uploadFlie(that.data.imgList[0], 0);
                  } else {
                    that.subclockIn()
                  }
                }
              }
            })

          } else if (!this.data.dktype.ds) {
            var that = this;
            wx.showModal({
              title: "提示",
              content: "您距离工作地点较远，您确定要工作打卡吗",
              success: function (res) {
                if (res.confirm) {
                  if (that.data.imgList.length > 0) {
                    that.uploadFlie(that.data.imgList[0], 0);
                  } else {
                    that.subclockIn()
                  }
                }
              }
            })
          } else {

            if (this.data.imgList.length > 0) {
              that.uploadFlie(this.data.imgList[0], 0);
            } else {
              this.subclockIn()
            }
          }

        } else if (this.data.gwInfo.type == 2) {
          console.log("---2---", this.data.dktype.ds)
          if (!this.data.dktype.ds) {
            var that = this;
            wx.showModal({
              title: "提示",
              content: "您距离工作地点较远，您确定要工作打卡吗",
              success: function (res) {
                if (res.confirm) {
                  if (that.data.imgList.length > 0) {
                    that.uploadFlie(that.data.imgList[0], 0);
                  } else {
                    that.subclockIn()
                  }
                }
              }
            })
          } else {
            console.log("---4--")
            if (this.data.imgList.length > 0) {
              console.log("---5--")
              this.uploadFlie(this.data.imgList[0], 0);
            } else {
              console.log("---3---")
              this.subclockIn()
            }
          }
        }
        // this.subclockIn()
      }

    }


  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    console.log("----------", this.data.imgList);
  },
  onclickscp: function (e) {
    let src = e.currentTarget.dataset.src;
    wx.previewImage({
      current: src,
      urls: this.data.imgList,
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    clearInterval(timeid)
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var shareObj = {
      title: "分享岗位", // 默认是小程序的名称(可以写slogan等)
      path: getApp().globalData.userInfo.inviteCode?'/pages/index/index?code='+getApp().globalData.userInfo.inviteCode:'/pages/index/index', // 
      imageUrl: '',
      success: function (res) {
        // 转发成功之后的回调
        if (res.errMsg == 'shareAppMessage:ok') {
  
  
        }
      }
    }
    console.log("------------", shareObj);
    // 返回shareObj
    return shareObj;
  },
  tabchange(e){
    this.setData({
      tabActive:e.detail.name
    })
    if(e.detail.name==2){
      this.getMore();
    }
  },
  getMore(){
    let params={}
    getMore.bind(this,'getJob',params,res=>{
      console.log(res)
    })()
  }
})